package com.fh.controller.loantask;

import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fh.annotation.SysLog;
import com.fh.model.ZTree;
import com.fh.service.system.user.UserService;
import com.fh.util.*;
import com.ybd.common.mask.MaskTypeEnum;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.fh.controller.base.BaseController;
import com.fh.model.Page;
import com.fh.model.loan.SysUser;
import com.fh.service.assign_out.IAssignOutService;
import com.fh.service.loantaskimpl.LoanTaskToBeServiceImpl;
import com.fh.service.loantaskimpl.LoanTaskUnderServiceImpl;


/**
 * LiGuangYi
 * 催收中controller
 *
 * @author dell、
 */
@Controller
@RequestMapping(value = "/taskdetails")
public class LoanTaskUnderController extends BaseController {
    private Logger logger = org.slf4j.LoggerFactory.getLogger(LoanTaskUnderController.class);

    @Autowired
    private LoanTaskUnderServiceImpl loanTaskUnderServiceImpl;
    @Autowired
    private IAssignOutService service;

    @Autowired
    private UserService userService;

    @Autowired
    private LoanTaskToBeServiceImpl loanTaskToBeService;

    /**
     * 任务列表
     *
     * @param page
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/list")
    public ModelAndView loanList(Page page, HttpServletRequest request) throws Exception {
        ModelAndView mv = this.getModelAndView();
        PageData pageData = loanTaskToBeService.setPdWithTrim(this.getPageData());
        Map<String, String> map1 = UserUtils.getCurrentRole();
        Integer quanXian1 = Integer.valueOf(map1.get(Const.SESSION_QX1));
        Integer quanXian3 = Integer.valueOf(map1.get(Const.SESSION_QX3));
        Integer quanXian4 = Integer.valueOf(map1.get(Const.SESSION_QX4));
        Integer quanXian5 = Integer.valueOf(map1.get(Const.SESSION_QX5));
        request.getSession().setAttribute("ppd", pageData);
        // 获取页面参数
        page.setPd(UserUtils.setDataRole(pageData, userService));
        String callUserName = pageData.getString("usname");
        SysUser sysUser = loanTaskUnderServiceImpl.getcallUserName(callUserName);

        if (sysUser != null) {
            loanTaskUnderServiceImpl.getUserId(pageData, sysUser);
        }
        String overValue = pageData.getString("overValue");
        String overValueByDay = pageData.getString("overValueByDay");
        String sortbylasttime = pageData.getString("sortbylasttime");
        if (!StringUtils.isEmpty(overValue)) {
            if (Const.SING_STATUS_STRING_ZERO.equals(overValue)) {
                pageData.put("sortsql", "a.overdue_amount,a.id");
                mv.addObject("overValueByAmt", Const.SING_STATUS_ZERO);
            } else if (Const.SIGN_STATUS_STRING_ONE.equals(overValue)) {
                pageData.put("sortsql", "a.overdue_amount DESC,a.id");
                mv.addObject("overValueByAmt", Const.SIGN_STATUS_ONE);
            }
        } else if (!StringUtils.isEmpty(overValueByDay)) {
            if (Const.SIGN_STATUS_STRING_TWO.equals(overValueByDay)) {
                pageData.put("sortsql", "a.overdue_date,a.id");
                mv.addObject("overValueByDate", Const.SIGN_STATUS_TWO);
            } else if (overValueByDay.equals(Const.SIGN_STATUS_STRING_THREE)) {
                pageData.put("sortsql", "a.overdue_date DESC,a.id");
                mv.addObject("overValueByDate", Const.SIGN_STATUS_THREE);
            }
        } else if (!StringUtils.isEmpty(sortbylasttime)) {
            if (Const.SING_STATUS_STRING_ZERO.equals(sortbylasttime)) {
                pageData.put("sortsql", "a.last_call_time,a.id");
                mv.addObject("sortbylasttime", Const.SING_STATUS_STRING_ZERO);
            } else if (sortbylasttime.equals(Const.SIGN_STATUS_STRING_ONE)) {
                pageData.put("sortsql", "a.last_call_time DESC,a.id");
                mv.addObject("sortbylasttime", Const.SIGN_STATUS_STRING_ONE);
            }
        } else {
            pageData.put("sortsql", "a.create_time DESC,a.id");
        }
        page.setPd(pageData);
        List<PageData> pagelist = loanTaskUnderServiceImpl.findLoanTaskListPage(page);
        Map<String, MaskTypeEnum> properties = new HashMap<>();
        properties.put(Const.TELE_PHONE, MaskTypeEnum.MOBILE);
        properties.put(Const.CONT_ID_CARD2, MaskTypeEnum.IDCARD2);
        if (pagelist.size() != 0) {
            //加密
            CoverUtil.setListCover(pagelist, properties);
        }
        mv.addObject("pd", pageData);
        mv.addObject("pagelist", pagelist);
        mv.setViewName("loantask/cuishouzhonglist");
        mv.addObject(Const.SESSION_QX1, quanXian1);
        mv.addObject(Const.SESSION_QX3, quanXian3);
        mv.addObject(Const.SESSION_QX4, quanXian4);
        mv.addObject(Const.SESSION_QX5, quanXian5);
        return mv;
    }

    /**
     * 标记
     *
     * @param request
     * @param ids     用户ID组 被标记
     * @param ids1    用户ID组 未标记
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/biaoji")
    @ResponseBody
    public Map<String, Object> doRemark(HttpServletRequest request, @RequestParam("ids") String[] ids,
                                        @RequestParam("ids1") String[] ids1) throws Exception {
        Map<String, Object> map = loanTaskUnderServiceImpl.getLabel(request, ids, ids1);
        return map;
    }

    /**
     * 分配页面
     *
     * @param id       用户id组
     * @param request
     * @param response
     * @param flag     值为1表示从待催收页面进行批量分派的
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/plliangfenpailist")
    public ModelAndView pilianglist(@RequestParam(value = "fpId", required = false) String[] id, HttpServletRequest request,
                                    HttpServletResponse response, @RequestParam(required = false) String total, @RequestParam(required = false) String flag,@RequestParam(value = "status",required = false)String status) throws Exception {

        ModelAndView mv = this.getModelAndView();
        // 获取当前用户id
        Integer currentUserId = UserUtils.getUser().getUSER_ID();
        List<SysUser> userpageS1 = loanTaskUnderServiceImpl.sysUsers(currentUserId, Const.GROUP_NAME_S1);
        List<SysUser> userpageS2 = loanTaskUnderServiceImpl.sysUsers(currentUserId, Const.GROUP_NAME_S2);
        List<SysUser> userpageS3 = loanTaskUnderServiceImpl.sysUsers(currentUserId, Const.GROUP_NAME_S2_ADD);
        request.getSession().setAttribute("fpId", id);
        mv.addObject("fpId", id);
        mv.addObject("len", id.length);
        mv.addObject("userpage1", userpageS1);
        mv.addObject("userpage2", userpageS2);
        mv.addObject("userpage3", userpageS3);
        mv.addObject("flag", flag);
        // 批量委外入库操作人
        mv.addObject("currentUserId", currentUserId);
        if ("auto".equals(flag)) {
            mv.addObject("status", status);
            mv.setViewName("loantask/autofenpai");
            mv.addObject("total", total);
        } else {
            mv.setViewName("loantask/piliangfenpai");

        }
        return mv;
    }

    /**
     * 批量分派
     *
     * @param userid
     * @param request
     * @param flag
     */
    @RequestMapping(value = "/pilianguser")
    public void piliangfpbangding(@RequestParam("userid") String userid, HttpServletRequest request,
                                  @RequestParam(required = false) String flag) {
        loanTaskUnderServiceImpl.getUserIdsByAssign(userid, request, flag);
    }


    /**
     * 导出Excel
     *
     * @param
     * @param
     * @throws Exception
     */
    @SysLog("任务管理-催收中Excel导出")
    @RequestMapping(value = "/daochuexcsz")
    public ModelAndView getExcel(Page page) throws Exception {
    	ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try{
			//检索条件===========
			PageData pageData = loanTaskToBeService.setPdWithTrim(this.getPageData());
			page.setPd(UserUtils.setDataRole(pageData, userService));
			//检索条件===========
			Map<String, Object> dataMap = service.MiddleExcel(page);
			ObjectExcelView erv = new ObjectExcelView("逾期客户表—催收中"); //执行excel操作
			mv = new ModelAndView(erv,dataMap);
		} catch(Exception e){
			logger.error(e.toString(), e);
		}
		return mv;
    }

    /**
     * 任务管理平均分派
     *
     * @param userid
     * @param request
     * @param flag
     */
    @RequestMapping(value = "/pilianguser2")
	@ResponseBody
    public void piliangfpbangding2(@RequestParam("userid") Integer[] userid, @RequestParam("totalTask") Integer totalTask, @RequestParam("fenpaiPagesize") Integer fenpaiPagesize, HttpServletRequest request,
                                   @RequestParam(required = false) String flag,@RequestParam(required = false)Integer status,@RequestParam(value = "useridStr",required = false)String useridStr) throws Exception {
        logger.info("pilianguser2 userid:" + userid + "totalTask:" + totalTask + "fenpaiPagesize:" + fenpaiPagesize);
        Integer taskNum;
        //如果总任务数小于fenpaiPagesize,需要分配的任务为fenpaiPagesize
        if (fenpaiPagesize > totalTask) {
            taskNum = totalTask;
        } else {
            taskNum = fenpaiPagesize;
        }

        Subject currentUser = SecurityUtils.getSubject();
        Session session = currentUser.getSession();
        Integer currentUserId = UserUtils.getUser().getUSER_ID();
        Page page = null;
        if (Objects.nonNull(status)) {
            if (0 == status) {
            	//委内平均分派
                page = (Page) session.getAttribute("page1");
                String[] ustr = useridStr.split(",");
				Integer[] u = new Integer[ustr.length];
				userid = Arrays.stream(ustr).map(m -> Integer.valueOf(m)).collect(Collectors.toList()).toArray(u);
            }else if (3==status){
            	//委外平均分派
                page = (Page) session.getAttribute("assignPage");
                page.getPd().put("sortFind","id DESC");
            }
        PageData pd = page.getPd();
        pd.put("status",status);
        pd.put("currentUserId",currentUserId);
        }
        loanTaskUnderServiceImpl.updataCallLoanInfoUserIds(page, userid, taskNum, request);


    }
	
	/**
	 * 委内 平均分派页面
	 */
	@RequestMapping("/avgDispatchedPage/{toTal}")
	public String acgDispatchedPage(Model model,@PathVariable String toTal){
		model.addAttribute("toTal",toTal);
		return "loantask/avgDispatch";
	}
	
	
	/**
	 * 委内 平均分派
	 * @throws Exception
	 */
	@RequestMapping(value = "/avgDispatched/{type}")
	@ResponseBody
	public Object avgDispatched(@PathVariable String type) throws Exception {
		// 获取当前用户id
		Integer currentUserId = UserUtils.getUser().getUSER_ID();
		//S1 S2 S2+
		List<SysUser> userpageS1 = loanTaskUnderServiceImpl.sysUsers(currentUserId, type);
		return  getTreeObj(userpageS1,type);
	}
	
	/**
	 * 获取上级对象
	 * @param id
	 * @return
	 */
	private SysUser getParent(String id){
		try {
			return loanTaskUnderServiceImpl.findObjByUserId(id);
		} catch (Exception e) {
			logger.error("getParentName --> ",e);
		}
		return null;
	}
	
	private List<ZTree> getTreeObj(List<SysUser> list,String type){
		Map<String ,List<SysUser>> map = list.stream().collect(Collectors.groupingBy(x->x.getParentid()));
		//root
		ZTree rootTree = new ZTree();
		rootTree.setOpen(true);
		rootTree.setName(type);
		//存储 各组的组长节点
		List<ZTree> rootChild = new ArrayList<>();
 		for(Map.Entry<String ,List<SysUser>> entry : map.entrySet()){
			SysUser parent = getParent(entry.getKey());
			List<SysUser> child = entry.getValue();
			//组长
			ZTree parentTree = new ZTree();
			parentTree.setId(parent.getUserid());
			parentTree.setOpen(true);
			parentTree.setName("主管："+parent.getName());
			//存储 组长下的催收员
			List<ZTree> parentChild = child.stream().map(x -> {
				//催收员
				ZTree childTree = new ZTree();
				childTree.setId(x.getUserid());
				childTree.setName(x.getName());
				return childTree;
			}).collect(Collectors.toList());
		 	parentTree.setChildren(parentChild);
			rootChild.add(parentTree);
		}
		rootTree.setChildren(rootChild);
		List<ZTree> tree = new ArrayList<>();
		tree.add(rootTree);
		return tree;
	}

}
